<script lang="ts" setup name="GoodsImage">
import { PropType, ref, computed } from 'vue'
import { GoodsInfo } from '@/types/data.d'
import { useMouseInElement } from '@vueuse/core'

defineProps({
  goodsInfo: {
    type: Object as PropType<GoodsInfo>,
    required: true
  }
})
const currIndex = ref(0)
const target = ref(null)
const { isOutside, elementX, elementY } = useMouseInElement(target)
const positionObj = computed(() => {
  const obj = {
    x: elementX.value - 100,
    y: elementY.value - 100
  }
  // 左边限制
  if (obj.x < 0) {
    obj.x = 0
  }
  // 右边限制
  if (obj.x > 200) {
    obj.x = 200
  }
  // 上边限制
  if (obj.y < 0) {
    obj.y = 0
  }
  // 下边限制
  if (obj.y > 200) {
    obj.y = 200
  }

  return obj
})
/*
1:具体哪里做不出来
2：做了什么努力
3：有没有解决方案

解决复杂的问题也是这样
1: 小块块显示与消失
2：小块块鼠标跟随（鼠标在小块块的中间位置）
3：上下左右范围限制
4：大图片展示
5：大图片跟随移动
*/
</script>
<template>
  <div class="goods-image">
    <div
      class="large"
      v-show="!isOutside"
      :style="[
        {
          backgroundImage: `url(${goodsInfo.mainPictures[currIndex]})`,
          backgroundPosition: `${-2 * positionObj.x}px ${-2 * positionObj.y}px`
        }
      ]"
    ></div>
    <div class="middle" ref="target">
      <img :src="goodsInfo.mainPictures[currIndex]" alt="" />
      <div
        class="layer"
        v-show="!isOutside"
        :style="{
          left: positionObj.x + 'px',
          top: positionObj.y + 'px'
        }"
      ></div>
    </div>
    <ul class="small">
      <li
        v-for="(item, index) in goodsInfo.mainPictures"
        :key="index"
        :class="{ active: index === currIndex }"
        @mouseenter="currIndex = index"
      >
        <img :src="item" alt="" />
      </li>
    </ul>
  </div>
</template>

<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  z-index: 500;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }

  .middle {
    width: 400px;
    height: 400px;
    position: relative;
    cursor: move;
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, 0.2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
